/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


var selectedKid = 1;
var editor;
$(document).ready(function() {
    //init rich text editor

   KindEditor.ready(function(K) {
            editor = K.create('#editor_note', {
                langType : 'en'
            });
    });

    //time selectors
    $('.time').ptTimeSelect();
    
    //hide all edit buttons of components
    $("div.edit").slideUp();
    
    //ratings
    $('#foodscore').raty({
        path: "/ukkepuk/source/html/css/images/",
        half: true,
        hintList:		['heel slecht', 'slecht', 'gemiddeld', 'goed', 'zeer goed']
    });

    //if you clikc on an image thumb, load this kid
    $(".kidthumbtile").click(function(){
        //reset objects
        $(".calendarkids").css("display","none");
        $(".kidstoday").css("display","none");
        $("#kiddiaper").css("display","block");
        $("#kidnote").css("display","block");
        $("div.overview").css("display","block");
        $("div.edit").css("display","none");
        //read data
        var selectedIndex = $(this).attr("id").substring(4);
        $.ajax({
            url: 'kid_actions.php',
            type: "POST",
            data: {kidId: selectedIndex, action: "readKidForCreche"},
            dataType: "xml",
            success: function(data) {
                //$('.result').html(data);
                //remove info of other kids
                $("#diaperstoday > .overview > table tr").remove();
                $("#sleeptoday > .overview > table tr").remove();
                $("#drinktoday > .overview > table tr").remove();
                $("#foodtoday > .overview > table tr").remove();


                //set info of kid
                //set name
                $("#firstname").html($(data).find("kid").attr("firstname"));
                $("#name").html($(data).find("kid").attr("name"));
                
                //set in out
                $("#kidInToday > .overview").html($(data).find("kid").attr("in"));
                $("#kidOutToday > .overview").html($(data).find("kid").attr("out"));

                $("#kiddate").html(formatDateKey($(data).find("kid").attr("date")));
                selectedKid = $(data).find("kid").attr("id");

                //set diaper info
                $(data).find("diaper").each( function() {
                    $("<tr><td>"+$(this).attr("time") + "</td></tr>").appendTo("#diaperstoday > .overview > table");
                });

                //set sleep info
                $(data).find("sleep").each( function() {
                    
                    $("<tr><td class=\"from\">"+$(this).attr("sleepFrom") + "</td><td class=\"to\">"+$(this).attr("sleepTo")+"</td></tr>").appendTo("#sleeptoday > .overview > table");
                });

                //set drink info
                $(data).find("drink").each( function() {
                    $("<tr><td>"+$(this).attr("timeFrom") + "</td><td>" + $(this).attr("timeTo") + "</td><td>" + $(this).attr("type") + "</td><td>" + $(this).attr("amount") + "cc</td></tr>").appendTo("#drinktoday > .overview > table");
                });

                //set food info
                $(data).find("food").each( function() {
                    $("<tr><td>" + $(this).attr("timeFrom") + "</td><td>" + $(this).attr("timeTo") + "</td><td>" + $(this).attr("title") + "</td><td>" + $(this).attr("score") + "</td> </tr>").appendTo("#foodtoday > .overview > table");
                });
                
                //set in out
                

            }
        });

        //set calendar
        var datetoday = new Date();
        loadCalendar(selectedIndex, datetoday.getYear()+1900, datetoday.getMonth()+1);

        //set next week calendar
        loadCalendarNextWeek(selectedIndex);

        //set text editor content.
        loadEditorNote(selectedIndex);

    });

    //if you click on an edit image, displayu the next line to add a line
    $("img.edit").click(function() {
        $(this).parent().parent().find(".time").attr("value", getTime());
        $(this).parent().parent().find(".overview").slideUp();
        //tab edit to slide down
       var tabindex = $(this).siblings("input[name='edittab']").attr("value");
       if(tabindex == null)
           tabindex = "edit";
       else
           tabindex = "tab"+tabindex;
        
        $(this).parent().parent().find("."+tabindex).slideDown();
    });

    //click on calendar day
    $("#kidcalendarmonth .open").click(function (){
        addTimeToCalendar(this);
    });

});

function formatDateKey(key){
    var year = key.substring(0, 4);
    var month = key.substring(4, 6);
    var day = key.substring(6, 8);

    return day + "/" + month + "/" + year;
}

function loadEditorNote(selectedIndex) {
    $.ajax({
        url: 'kid_actions.php',
        type: "POST",
        data: {kidId: selectedIndex, action: "readNoteForKids"},
        dataType: "xml",
        success: function(data) {
            editor.html($(data).find("report").text());
        }
    });


}
function loadCalendarNextWeek(selectedIndex){
    $.ajax({
        url: 'calendar_actions.php',
        type: "POST",
        data: {kidId: selectedIndex, numDays: 7, action: "readNextCalendarDaysForKid"},
        dataType: "xml",
        success: function(data) {
             $("#weekcalendar .weekcalendar").remove();
            var result = "<table class=\"weekcalendar\">";
            result += "<tr><th>Volgende " + 7 + " dagen</th></tr>"
            $(data).find("calendar").each( function() {

                var timeString = "-";
                if( $(this).attr("registeredDay") == "yes")
                    timeString = $(this).attr("startTime") + " --> " + $(this).attr("endTime");

                result += "<tr><td>" + formatDateKey( $(this).attr("date")) + "</td><td>" + timeString + "</td></tr>";
            });
            result += "</table>";
            $(result).appendTo("#weekcalendar");
        }
    });
}

function loadCalendar(selectedIndex, yearToLoad, monthToLoad){
    $.ajax({
        url: 'calendar_actions.php',
        type: "POST",
        data: {kidId: selectedIndex, year: yearToLoad, month: monthToLoad, action: "readCalendarForKid"},
        dataType: "xml",
        success: function(data) {
            $("#kidcalendarmonth .monthcalendar").remove();

            var result = "<table class=\"monthcalendar\">";
            var prevCalYear = yearToLoad;
            var prevCalMonth = monthToLoad - 1;

            var nextCalYear = yearToLoad;
            var nextCalMonth = monthToLoad + 1;
            if(monthToLoad == 1){
                prevCalMonth = 12;
                prevCalYear -= 1;
            }else if (monthToLoad == 12) {
                nextCalMonth = 1;
                nextCalYear += 1;
            }
            result += "<tr><th><a href=\"javascript:loadCalendar("+selectedIndex+","+prevCalYear+","+prevCalMonth+")\">&lt;&lt;</a></th><th colspan=\"5\">"+$(data).find("calendarMonth").attr("monthLabel") + " " + $(data).find("calendarMonth").attr("year") +"</th><th><a href=\"javascript:loadCalendar("+selectedIndex+","+nextCalYear+","+nextCalMonth+")\">&gt;&gt;</a></th></tr>";
            result += "<tr><th>Ma</th><th>Di</th><th>Wo</th><th>Do</th><th>Vr</th><th>Za</th><th>Zo</th></tr>";
            result += "<tr>";

            var index = 1;
            $(data).find("calendarDayparts").each( function() {
                var calDayClass = "open";
                if($(this).attr("registeredDay") == "yes")
                    calDayClass = "registeredDay";
                result += "<td id=\"c_"+ $(this).attr("date") +"\" class=\""+calDayClass + " " + $(this).attr("itemType") + "\">" + $(this).attr("date").substring(6) + "</td>";
                if(index%7 == 0)
                    result += "</tr><tr>";
                index++;
            });
            result += "</tr>";
            result += "</table>";
            $(result).appendTo("#kidcalendarmonth #calendar");

            //set default start and stop
            $("#fromTime").attr("value", ($(data).find("calendarMonth").attr("defaultStart")));
            $("#toTime").attr("value", ($(data).find("calendarMonth").attr("defaultEnd")));

            //loop again over xml to add hover
            $(data).find("calendarDayparts").each( function() {
                if($(this).attr("registeredDay") == "yes"){
                    $("#c_" + $(this).attr("date")).bind("mouseover", {me:$(this)}, 
                        function (event) { 
                            var selectedDay = event.data.me.attr("date").substring(6);
                            var html = "";
                            $(event.data.me).find("daypart").each( function() {
                                
                                html += $(this).attr("startTime") + " --> " + $(this).attr("endTime") + "<br/>";
                            });
                            $("#selectedTime").html("op " +selectedDay + ": <br/> " + html);
                            //$("#selectedTime").html("op " +selectedDay + ": <br/> " +event.data.me.attr("startTime") + " -> " + event.data.me.attr("endTime"));
                        });

                }
            });

            //registere event listener to open days of this month
            $("#kidcalendarmonth .open.this").click(function (){
                 addTimeToCalendar(this);
            });
            
            $("#kidcalendarmonth .registeredDay.this").click(function (){
                 addTimeToCalendar(this);
            });
        }

    });


}



function getTime() {
    var now = new Date();
    var hrs = now.getHours();
    if(hrs < 10)
        hrs =  "0" + hrs;
    var mins = now.getMinutes();
    if(mins < 10)
        mins = "0" + mins;
    var timeNow = hrs + ":" + mins;
    return timeNow;
}

//add a diper
function addDiaper() {
    $("#kiddiaper div.edit").slideUp();
    $("#kiddiaper .overview").slideDown();
        
    $.ajax({
        url: 'kid_actions.php',
        type: "POST",
        data: {kidId: selectedKid, dType: 1, dTimestamp: $("#diapertime").attr("value"), action: "addDiaper"},
        dataType: "xml",
        success: function(data) {
            //$('.result').html(data);

            if($(data).find("result").attr("status") == "error"){
                $(".errormsg").html($(data).find("error").attr("descr"));
            }
            else if($(data).find("result").attr("status") == "ok"){
                //handle success
                var time = $(data).find("diapers").attr("time");
                $("<tr><td>"+ time + "</td></tr>").appendTo("#diaperstoday > .overview > table");
            }
        }
    });
}



function addInTime() {
    $("#kidInOut div.edit").slideUp();
    $("#kidInOut .overview").slideDown();
    
    $.ajax({
        url: 'kid_actions.php',
        type: "POST",
        data: {kidId: selectedKid, inTime: $("#inTime").attr("value"), action: "saveTimeIn"},
        dataType: "xml",
        success: function(data) {
            if($(data).find("result").attr("status") == "error"){
                $(".errormsg").html($(data).find("error").attr("descr"));
            }
            else if($(data).find("result").attr("status") == "ok"){
                //handle success
                var time = $(data).find("kidInOut").attr("inTime");
                $("#kidInToday > .overview ").html(time);
            }
        }
    });
}

function addOutTime() {
    $("#kidInOut div.edit").slideUp();
    $("#kidInOut .overview").slideDown();
    
    $.ajax({
        url: 'kid_actions.php',
        type: "POST",
        data: {kidId: selectedKid, outTime: $("#outTime").attr("value"), action: "saveTimeOut"},
        dataType: "xml",
        success: function(data) {
            if($(data).find("result").attr("status") == "error"){
                $(".errormsg").html($(data).find("error").attr("descr"));
            }
            else if($(data).find("result").attr("status") == "ok"){
                //handle success
                var time = $(data).find("kidInOut").attr("outTime");
                $("#kidOutToday > .overview ").html(time);
            }        
        }
    });
}

function addDrink(step) {
    $("#kiddrink div.edit").slideUp();
    $("#kiddrink .overview").slideDown();

    var params = null;
    if(step == 'from'){
        params = {kidId: selectedKid, lTimestamp: $("#drinktimefrom").attr("value"), lType: $("#drinktype").attr("value"), action: "addDrinkFrom"};
    }
    else if(step == 'to'){
        params = {kidId: selectedKid, lTimestamp: $("#drinktimeto").attr("value"), lAmount: $("#drinkamount").attr("value"), action: "addDrinkTo"};
    }
    
    $.ajax({
        url: 'kid_actions.php',
        type: "POST",
        data: params,
        dataType: "xml",
        success: function(data) {
            //$('.result').html(data);
            if($(data).find("result").attr("status") == "error"){
                $(".errormsg").html($(data).find("error").attr("descr"));
            }
            else if($(data).find("result").attr("status") == "ok"){
                //handle success
                var timeFrom = $(data).find("drink").attr("timeFrom");
                var timeTo = $(data).find("drink").attr("timeTo");
                var type = $(data).find("drink").attr("drinkTypeString");
                var amount = $(data).find("drink").attr("amount");
                var begin = $(data).find("drink").attr("begin");
                if(begin == "yes"){
                    $("<tr><td>"+timeFrom + "</td><td class=\"to\">...</td><td>" + type + "</td><td class=\"amount\"></td></tr>").appendTo("#drinktoday > .overview > table");
                    $("#drinkimage input[name='edittab']").attr("value", "2");
                }
                else{
                    $("#drinktoday  td.to").each(function () {
                        if($(this).text() == "..."){
                            $(this).text(timeTo);

                        }
                    });
                    $("#drinktoday  td.amount").each(function () {
                         if($(this).text() == ""){
                            $(this).text(amount);
                         }
                    });
                    $("#drinkimage input[name='edittab']").attr("value", "1");                    
                }
                
            }
        }
    });
}

function addFood(step) {
    $("#kidfood div.edit").slideUp();
    $("#kidfood .overview").slideDown();
    
    //set post parameters
    var params = null;
    if(step == "from")
        params = {kidId: selectedKid, fTimestamp: $("#foodtimefrom").attr("value"), fMenu: $("#foodmenu").attr("value"), action: "addFoodFrom"};
    else if(step == "to")
        params = {kidId: selectedKid, fTimestamp: $("#foodtimeto").attr("value"), fScore: $("#foodscore").raty('score'), action: "addFoodTo"};
    
    
    $.ajax({
        url: 'kid_actions.php',
        type: "POST",
        data: params,
        dataType: "xml",
        success: function(data) {
            //$('.result').html(data);
            if($(data).find("result").attr("status") == "error"){
                $(".errormsg").html($(data).find("error").attr("descr"));
            }
            else if($(data).find("result").attr("status") == "ok"){
                //handle success
                var timeFrom = $(data).find("food").attr("timeFrom");
                var timeTo = $(data).find("food").attr("timeTo");
                var menu = $(data).find("food").attr("recipeString");
                var score = $(data).find("food").attr("score");
                var begin = $(data).find("food").attr("begin");
                if(begin == "yes"){
                    $("<tr><td>" + timeFrom + "</td><td class=\"to\">...</td><td>" + menu + "</td><td class=\"score\"></td></tr>").appendTo("#foodtoday > .overview > table");
                    $("#foodimage input[name='edittab']").attr("value", "2");
       
                }else {
                    $("#foodtoday  td.to").each(function () {
                        if($(this).text() == "..."){
                            $(this).text(timeTo);

                        }
                    });
                    $("#foodtoday  td.score").each(function () {
                         if($(this).text() == ""){
                            $(this).text(score);
                         }
                    });
                    $("#foodimage input[name='edittab']").attr("value", "1");
                }
            }
        }
    });
}

function addSleep(step) {
    $("#kidsleep div.edit").slideUp();
    $("#kidsleep .overview").slideDown();
    //set post parameters
    var params = null;
    if(step == "from")
        params = {kidId: selectedKid, sTimestamp: $("#sleeptimefrom").attr("value"), action: "addSleepFrom"};
    else if(step == "to")
        params = {kidId: selectedKid, sTimestamp: $("#sleeptimeto").attr("value"), action: "addSleepTo"};
    
    $.ajax({
        url: 'kid_actions.php',
        type: "POST",
        data: params,
        dataType: "xml",
        success: function(data) {
            //$('.result').html(data);
            if($(data).find("result").attr("status") == "error"){
                $(".errormsg").html($(data).find("error").attr("descr"));
            }
            else if($(data).find("result").attr("status") == "ok"){
                //handle success
                var timeFrom = $(data).find("sleep").attr("timeFrom");
                var timeTo = $(data).find("sleep").attr("timeTo");
                var begin = $(data).find("sleep").attr("begin");
                if(begin == "yes"){
                    $("<tr><td class=\"from\">"+ timeFrom + "</td><td class=\"to\">"+"..."+"</td></tr>").appendTo("#sleeptoday > .overview > table");
                    //set tabindex to 2
                     $("#sleepimage input[name='edittab']").attr("value", "2");
       
                } else {
                    $("#sleeptoday  td.to").each(function () {
                        if($(this).text() == "..."){
                            $(this).text(timeTo);

                        }
                    });
                    //set tabindex back to 1
                    $("#sleepimage input[name='edittab']").attr("value", "1");
                }
            }
        }
    });
}

 function saveNote() {

    $.ajax({
        url: 'kid_actions.php',
        type: "POST",
        data: {kidId: selectedKid, notedata: editor.html(), action: "saveNote"},
        dataType: "xml",
        success: function(data) {
            //$('.result').html(data);
            if($(data).find("result").attr("status") == "error"){
                $(".errormsg").html($(data).find("error").attr("descr"));
            }
            else if($(data).find("result").attr("status") == "ok"){
                //handle success

            }
        }
    });
}



function addTimeToCalendar(obj) {
    
    $.ajax({
        url: 'calendar_actions.php',
        type: "POST",
        data: {addtype:$('input:radio[name=addtype]:checked').val(), kidId: selectedKid, cDate: $(obj).attr("id").substring(2),  cStartTime: $("#fromTime").attr("value"), cEndTime: $("#toTime").attr("value"), action: "addTime"},
        dataType: "xml",
        success: function(data) {
            //$('.result').html(data);
            if($(data).find("result").attr("status") == "error"){
                $(".errormsg").html($(data).find("error").attr("descr"));
            }
            else if($(data).find("result").attr("status") == "ok"){
                //handle success
                var date = $(data).find("calendar").attr("date");
                $("#c_"+date).attr("class", "registered");

                loadCalendarNextWeek(selectedKid);
            }
        }
    });
}